<template>
  <div class="app-container">
    <el-col :span="24" class="title-row">
      <span>| 新增绿地范围</span>
    </el-col>
    <el-form
      id="elForm"
      ref="elForm"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="110px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入名称"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入地址"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="绿地大类" prop="category_type">
            <el-select
              v-model="formData.category_type"
              placeholder="请选择绿地大类"
              clearable
              :style="{ width: '100%' }"
              @change="handleChangeType"
            >
              <el-option
                v-for="dict in typeOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="绿地中类" prop="medium_type">
            <el-select
              v-model="formData.medium_type"
              placeholder="请选择绿地中类"
              clearable
              :style="{ width: '100%' }"
              @change="handleChangeTypem"
            >
              <el-option
                v-for="dict in typemOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供水方式" prop="water_supply">
            <el-select
              v-model="formData.water_supply"
              placeholder="请选择供水方式"
              multiple
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in dict.type.sys_guangms"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供水水源" prop="water_source">
            <el-select
              v-model="formData.water_source"
              placeholder="请选择供水水源"
              clearable
              multiple
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in dict.type.sys_guangsy"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="与三调数据对比" prop="sjly">
            <el-input
              v-model="formData.sjly"
              placeholder="请输入与三调数据对比结果"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="信息记录备注" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入信息记录备注"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm" icon="el-icon-check"
          >提交</el-button
        >
        <el-button @click="resetForm">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-circle-close"
          @click="cancel"
          >返回</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Sketch from "@arcgis/core/widgets/Sketch";
import { v4 as uuidv4 } from "uuid";
import { addAttach } from "../../../api/attachment/attach";
import { mapActions,mapGetters } from "vuex";
export default {
  props: {
    paramObj: { default: () => {} },
    mapview: { default: () => {} },
  },
  inject: ["toggleComponent"],
  dicts: [
    "sys_greenland_type",
    "sys_greenland_type_m",
    "sys_greenland_type_s",
    "sys_guangms",
    "sys_guangsy",
  ],
  data() {
    var checkZhandmj = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入占地面积"));
      }
      if (!isFinite(value)) {
        return callback(new Error("请输入数字值"));
      } else callback();
    };
    return {
      picFileList: [],
      // 必须给formData对象的属性设置对应空值，否则重置后无法输入数据
      formData: {
        name: "",
        address: "",
        category_type: "",
        medium_type: "",
        water_supply: "",
        water_source: "",
        remark: "",
        sjly:"",
      },
      rules: {
        objectid: [],
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
        category_type: [
          {
            required: true,
            message: "请选择一个绿地大类",
            trigger: "change",
          },
        ],
        medium_type: [
          {
            required: false,
            message: "请选择一个绿地中类",
            trigger: "change",
          },
        ],
        water_supply: [
          {
            required: true,
            message: "请选择供水方式",
            trigger: "change",
          },
        ],
        water_source: [
          {
            required: true,
            message: "请选择供水水源",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            message: "请输入地址",
            trigger: "blur",
          },
        ],
        remark: [
          {
            // required: true,
            message: "请输入信息记录备注",
            trigger: "blur",
          },
        ],
        sjly: [
          {
            // required: true,
            message: "请输入与三调对比结果",
            trigger: "blur",
          },
        ],
      },
      feature: undefined,
      selectedGraphic: undefined,
      udpateGraphicsLayer: undefined,
      dialogImageUrl: "",
      dialogVisible: false,
      deleteAttachmentIds: [],
      addAttachments: [],
      sketch: undefined,
      addGraphics: [],
      // 绿地大类
      typeOptions: [],
      // 绿地中类
      typemOptions: [],
      // 绿地小类
      typesOptions: [],
    };
  },
  activated() {
    let _self = this;
    _self.feature = this.paramObj.feature;
    _self.featureLayer = this.paramObj.featureLayer;
    _self.addAttachments = [];
    // 显示图形编辑面板
    _self.addGeometry();
  },
  computed: { ...mapGetters(["nickName","deptId"]),},
  deactivated() {
    this.clearGraphics();
  },
  created() {
    // axios.get("/config/city.json").then((res) => {
    //   this.suosjdOptions = res.data;
    // });
    // axios.get("/config/types.json").then((res) => {
    //   this.typeOptions = res.data;
    // });
    this.suosjdOptions = city;
    this.typeOptions = types;
  },
  mounted() {},
  methods: {
    // 获取要删除的附件id
    handleRemove(file, fileList) {
      console.log(file);
      // 如果是附件列表里存在则添加到待删除附件列表里
      if (file.url != undefined && file.url.indexOf("attachfiles") > 0)
        this.deleteAttachmentIds.push(file.id);
      this.addAttachments = this.addAttachments.filter(
        (val) => val.uid !== file.uid
      );
    },

    // 获取
    handleChange(file, fileList) {
      this.addAttachments.push(file);
      console.log(this.addAttachments);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 街道选择
    handleChangeSuosjd(value) {
      if (value == "") {
        this.suossqOptions = [];
        return;
      }
      this.suossqOptions = this.suosjdOptions.filter(
        (item) => item.value == value
      )[0].children;
    },
    // 绿地大类选择
    handleChangeType(value) {
      if (value == "") {
        this.typemOptions = [];
        return;
      }
      this.typemOptions = this.typeOptions.filter(
        (item) => item.value == value
      )[0].children;
    },
    // 绿地中类选择
    handleChangeTypem(value) {
      if (value == "") {
        this.typesOptions = [];
        return;
      }
      this.typesOptions = this.typemOptions.filter(
        (item) => item.value == value
      )[0].children;
    },
    submitForm() {
      let _self = this;
      const attachGroupId = uuidv4();
      _self.$refs["elForm"].validate((valid) => {
        if (!valid) return;
        if (_self.selectedGraphic == undefined) {
          _self.$message.error("请添加空间位置信息");
          return;
        }
        console.log(_self.formData.water_source);
        // 新增要素
        const attributes = {
          name: _self.formData.name,
          address: _self.formData.address,
          category_type: _self.formData.category_type,
          medium_type: _self.formData.medium_type,
          water_supply: _self.formData.water_supply.toString(),
          water_source: _self.formData.water_source.toString(),
          remark: _self.formData.remark,
          sjlyL:_self.formData.sjly,
          collector: _self.nickName,
          dept_id :_self.deptId,
          hczt:0,
          collecttime: Date.now(),
        };
        const addFeature = new Graphic({
          geometry:
            _self.selectedGraphic == undefined
              ? ""
              : _self.selectedGraphic.geometry,
          attributes: attributes,
        });
        _self.featureLayer
          .applyEdits({
            addFeatures: [addFeature],
          })
          .then((editsResult) => {
            console.log(editsResult);
            if (_self.selectedGraphic)
              _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
            const objectId = editsResult.addFeatureResults[0].objectId;
            // 根据返回的objectid添加附件
            // _self.addAttachment(attachGroupId);
            _self.$message.success("新增成功");
            _self.cancel();
          });
      });
    },
    // 添加附件
    addAttachment(attachGroupId) {
      let _self = this;
      const formData = new FormData();
      _self.addAttachments.forEach((attach) => {
        formData.append("files", attach.raw);
      });
      formData.append("attachGroupId", attachGroupId);
      addAttach(formData).then((data) => {
        console.log(data);
      });
      // arcgis js api方法
      // if (_self.addAttachments.length > 0) {
      //   _self.addAttachments.forEach((attachment) => {
      //     console.log(attachment);
      //     addAttachment({
      //       url: _self.featureLayer.url + "/" + _self.featureLayer.layerId, // "http://vm.wskcy.cn/server/rest/services/midong/ldpc/FeatureServer/5",
      //       featureId: addObjectId,
      //       attachment: attachment.raw,
      //     }).then((response) => {
      //       console.log(response);
      //     });
      //   });
      // }
    },
    resetForm() {
      let _self = this;
      _self.$refs["elForm"].resetFields();
      _self.picFileList = [];
      // 删除临时图形
      if (_self.selectedGraphic)
        _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
      // 删除微件
      _self.mapview.ui.remove(_self.sketch);
      this.addGeometry();
    },
    // 更新空间位置
    addGeometry() {
      let _self = this;
      _self.udpateGraphicsLayer = new GraphicsLayer();
      _self.mapview.map.add(_self.udpateGraphicsLayer);
      _self.sketch = new Sketch({
        layer: _self.udpateGraphicsLayer,
        view: _self.mapview,
        // graphic will be selected as soon as it is created
        creationMode: "update",
      });
      // 设置绘图工具条显示要素
      _self.sketch.visibleElements = {
        createTools: {
          point: false,
          polyline: false,
          polygon: true,
          rectangle: false,
          circle: false,
        },
        selectionTools: {
          "lasso-selection": false,
          "rectangle-selection": false,
        },
        settingsMenu: false,
      };
      _self.sketch.create();
      _self.mapview.ui.add(_self.sketch, "top-right");
      _self.sketch.on("create", (event) => {
        if (event.state === "complete") {
          console.log("create complete");
          _self.selectedGraphic = event.graphic;
          _self.addGraphics.push(event.graphic);
          // 每个要素只有一个点，如果已创建的一个点，则不允许继续创建点。隐藏创建点按钮
          if (_self.addGraphics.length > 0)
            document.getElementsByClassName(
              "esri-sketch__section esri-sketch__tool-section"
            )[1].style.display = "none";
          // _self.mapview.graphics.add(event.graphic);
          // _self.mapview.ui.remove(_self.sketch);
        }
      });
      _self.sketch.on("update", (event) => {
        if (event.state === "complete") {
          console.log("update complete");
          if (event.graphics.length == 0) return;
          _self.selectedGraphic = event.graphics[0];
        }
      });
      _self.sketch.on("delete", (event) => {
        event.graphics.forEach((graphic) => {
          console.log("deleted", graphic);
          if (graphic == _self.selectedGraphic)
            _self.selectedGraphic = undefined;
          _self.addGraphics = _self.addGraphics.filter(
            (item) => item !== graphic
          );
        });
        // 如果没有添加任何点，就显示创建点按钮
        if (_self.addGraphics.length == 0)
          document.getElementsByClassName(
            "esri-sketch__section esri-sketch__tool-section"
          )[1].style.display = "";
      });
    },
    clearGraphics() {
      let _self = this;
      // 删除编辑微件
      _self.mapview.ui.remove(_self.sketch);
      // 移除编辑图层
      _self.mapview.map.layers.remove(_self.udpateGraphicsLayer);
    },
    cancel() {
      let _self = this;
      this.$refs["elForm"].resetFields();
      _self.picFileList = [];
      _self.clearGraphics();
      // 删除微件
      _self.mapview.ui.remove(_self.sketch);
      // 切换组件
      this.toggleComponent("dataPanel");
    },
  },
};
</script>

<style lang="scss" scoped>
.title-row {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  color: #11a983;
  margin-bottom: 1vh;
}

.header {
  display: flex;
  justify-content: space-between;
}

#domCart1 {
  width: 100%;
  height: 100%;
}

.el-upload__tip {
  line-height: 1.2;
}

::v-deep .el-form-item {
  margin-bottom: 20px;
}
</style>

<!-- [{
    "statisticType": "count",
    "onStatisticField": "OBJECTID",
    "outStatisticFieldName": "Count"
}] -->
